package com.xing.crm.web.controller;

import com.xing.crm.pojo.User;
import com.xing.crm.pojo.WebUser;
import com.xing.crm.service.UserService;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

/** 后台管理员登录，退出、修改密码
 * @author Mr.L
 * @version V1.0
 * @date 2021年07月21日 17:37
 */
@Controller
@RequestMapping({"/user"})
public class UserController
{
    @Resource
    private UserService userService;
    
    @PostMapping({"/login"})
    public String login(String account, String password, HttpSession session, Model model)
    {
        User user = this.userService.checkLogin(account, password);
        WebUser webUser = (WebUser) session.getAttribute("webUser");
        //20210906 增加同一浏览器不能同时登录用户端和管理端，不知会不会和MyWebConfig中的登录判断起冲突 ？
        //后来老板又让给去掉了，我也不知会不会发神经，这已经触及到我的知识盲区了
        //if(webUser!=null) {
        //    model.addAttribute("flag", "已经在当前浏览器登录了展示端用户");
        //    return "/admin/login";
        //}
        if (user == null) {
            model.addAttribute("flag", "用户名或密码错误");
            return "/admin/login";
        }
        session.setAttribute("user", user);
        return "redirect:/admin/index";
    }
    
    //退出登录
    @GetMapping({"/logout"})
    public String logout(HttpSession session)
    {
        session.removeAttribute("user");
        return "redirect:/admin/login";
    }
    //编辑
    @ResponseBody
    @RequestMapping("/edit")
    public Map<String, Object> updatePwd(String pwd, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if(user != null ) {
            user.setPassword(pwd);
        }
        Map<String, Object> result = userService.updatePwd(user);
        if(result.get("data") != null) {
            /* 修改成功，更新用户信息到session中 */
            session.setAttribute("user", result.get("data"));
        }
        return result;
    }
}
